import axios from "@/api/http"
import uri from "@/config/uri"
export default {
    namespaced: true,
    state: {
        curIndex: 1,
        articleNum: 0,
        perSize: 6,
        articleList: []
    },
    mutations: {
        setCurIndex(state, arg) {
            state.curIndex = arg
        },
        setArticleNum(state, arg) {
            state.articleNum = arg
        },
        setPerSize(state, arg) {
            state.perSize = arg
        },
        setArticleList(state, arg) {
            state.articleList = arg
        }
    },
    actions: {
        loadAllArticles(context) {
            axios.get(uri.getAll)
                .then((res) => {
                    context.commit("setArticleList", res.data)
                    context.commit("setArticleNum", res.data.length)
                    context.commit("setCurIndex", 1)
                })
                .catch((err) => {
                    context.commit("setArticleList", [])
                })
        },
        searchByKeyWord(context, param) {
            axios.post(uri.search, { kw: param })
                .then((res) => {
                    context.commit("setArticleList", res.data)
                    context.commit("setArticleNum", res.data.length)
                    context.commit("setCurIndex", 1)
                }).catch((err) => {
                    context.commit("setArticleList", [])
                })
        }
    },
    getters: {
        parseArticleList(state) {
            function condition(ele, index) {  //过滤条件
                return (index >= ((state.curIndex - 1) * state.perSize) && (index < state.curIndex * state.perSize) && (index < state.articleList.length))
            }
            return state.articleList.filter(condition)
        }
    }
}